package com.xunk.equipment.service.dnake.service.impl;

import com.xunk.common.core.utils.DataUtils;
import com.xunk.common.redis.service.RedisService;
import com.xunk.equipment.domain.EquipmentDO;
import com.xunk.equipment.service.BaseService;
import com.xunk.equipment.service.IEquipmentService;
import com.xunk.equipment.vo.response.DnakeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.xunk.common.core.domain.EquipmentResponse;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service("dnake-airSwitch")
@Slf4j
public class DnakeAirdeteServiceImpl implements IEquipmentService {

    @Autowired
    protected RedisService redisService;
    @Autowired
    @Lazy
    BaseService baseService;

    @Override
    public EquipmentResponse getEquipmentInfo(EquipmentDO equipmentDO) {
        String ancestor = baseService.findAncestorByDeptId(equipmentDO.getDeptId());
        String key = ancestor.concat(":").concat(equipmentDO.getDeviceSn());
        Map<String, Object> cacheMap = redisService.getCacheMap(key);
        DnakeResponse deviceResponse = new DnakeResponse();
        if (DataUtils.isNotEmpty(cacheMap)) {
            deviceResponse.setDeviceSn(equipmentDO.getDeviceSn());
            List<Map<String, Integer>> responseList = new LinkedList<>();

            int channels = Integer.parseInt(cacheMap.get("channels").toString());
            for (int i = 1; i <= channels; i++) {
                Map<String, Integer> response = new HashMap<>();
                response.put("devCh", i);
                int finalI = i;
                cacheMap.forEach((k, v) -> {
                    if (k.contains(finalI + ".")) {
                        response.put(k.substring(k.indexOf(finalI + ".") + 2), Integer.valueOf(String.valueOf(v)));
                    }
                });
                if (null != cacheMap.get(i + ".pm2.5") && null != cacheMap.get(i + ".pm1.0") && null != cacheMap.get(i + ".pm10")) {
                    response.remove("pm2.5");
                    response.remove("pm1.0");
                    response.remove("pm10");
                    response.put("pm25", Integer.valueOf(String.valueOf(cacheMap.get(i + ".pm2.5"))));
                    response.put("pm10", Integer.valueOf(String.valueOf(cacheMap.get(i + ".pm1.0"))));
                    response.put("pm100", Integer.valueOf(String.valueOf(cacheMap.get(i + ".pm10"))));
                }
                responseList.add(response);
            }

            deviceResponse.setSupplier(equipmentDO.getSupplier());
            deviceResponse.setCandidateModel(baseService.getCandidateModel(equipmentDO.getDeviceBaseId()));
            deviceResponse.setData(responseList);
        }
        return deviceResponse;
    }

}
